package cn.edu.bupt.blog.service;

import cn.edu.bupt.blog.NotFoundException;
import cn.edu.bupt.blog.dao.TagRepository;
import cn.edu.bupt.blog.po.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private TagRepository TagRepository;
    @Override
    public Tag saveTag(Tag Tag) {
        return TagRepository.save(Tag);
    }

    @Override
    public Tag getTag(Long id) {
        return TagRepository.getOne(id);
    }

    @Override
    public Tag getTagByName(String name) {
        return TagRepository.findByName(name);
    }

    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return TagRepository.findAll(pageable);
    }

    @Override
    public List<Tag> listTag() {
        return TagRepository.findAll();
    }

    @Override
    public List<Tag> listTag(String ids) {// ids格式 1,2,3
        // 根据id的集合获取标签对象的集合
        return TagRepository.findAllById(convertToList(ids));// findAll 需要的格式为数组
    }

    @Override
    public List<Tag> listTag(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0,size,sort);
        return TagRepository.findTop(pageable);
    }

    private List<Long> convertToList(String ids) {
        List<Long> list = new ArrayList<>();
        if (!"".equals(ids) && ids != null) {
            String[] idarray = ids.split(",");
            for (int i=0; i < idarray.length;i++) {
                list.add(new Long(idarray[i]));
            }
        }
        return list;
    }

    @Override
    public Tag updateTag(Long id, Tag Tag) {
        Tag t = TagRepository.getOne(id);
        if(t == null) {
            throw new NotFoundException("不存在该标签！");
        }
        BeanUtils.copyProperties(Tag,t);
        return TagRepository.save(t);
    }

    @Override
    public void deleteTag(Long id) {
        TagRepository.deleteById(id);
    }
}
